package com.kitty.mybatis.mybatisv1.executor.statement;

import com.kitty.mybatis.mybatisv1.executor.Executor;
import com.kitty.mybatis.mybatisv1.executor.rsultset.KittyResultSetHandler;
import com.kitty.mybatis.mybatisv1.mapping.KittyBoundSql;
import com.kitty.mybatis.mybatisv1.mapping.KittyMappedStatement;
import com.kitty.mybatis.mybatisv1.session.KittyConfiguration;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Description
 * @Author SHEN
 * @Date 2020/11/3
 */
public abstract class KittyBaseStatementHandler implements KittyStatementHandler {

    protected final KittyConfiguration configuration;
    protected final Executor executor;
    protected final KittyMappedStatement mappedStatement;
    protected final KittyResultSetHandler resultSetHandler;
    protected KittyBoundSql boundSql;


    protected KittyBaseStatementHandler(Executor executor, KittyMappedStatement mappedStatement,
                                        Object parameterObject, KittyBoundSql boundSql) {
        this.configuration = mappedStatement.getConfiguration();
        this.executor = executor;
        this.mappedStatement = mappedStatement;
        this.boundSql = boundSql;
        this.resultSetHandler = null;
    }

    @Override
    public Statement prepare(Connection connection) throws SQLException {
        Statement statement = null;
        try {
            statement = instantiateStatement(connection);
            setStatementTimeout(statement);
            setFetchSize(statement);
        }catch (SQLException e){
            closeStatement(statement);
            throw e;
        }


        return statement;
    }

    protected void closeStatement(Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            //ignore
        }
    }

    private void setFetchSize(Statement statement) throws SQLException {
        Integer fetchSize = mappedStatement.getFetchSize();
        if (fetchSize != null) {
            statement.setFetchSize(fetchSize);
        }
    }

    private void setStatementTimeout(Statement statement) throws SQLException {
        Integer timeout = mappedStatement.getTimeout();
        //todo 设置默认的timeout属性
        //Integer defaultTimeout = configuration.getDefaultStatementTimeout();
        if (timeout != null) {
            statement.setQueryTimeout(timeout);
        } /*else if (defaultTimeout != null) {
            statement.setQueryTimeout(defaultTimeout);
        }*/
    }

    protected abstract Statement instantiateStatement(Connection connection) throws SQLException;

}
